package com.cos.lession54.web.controller;

import com.cos.lession54.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: COS
 * @time: 2022/3/9 11:30
 * @description:
 */
@Controller
@RequestMapping("/ajax")
public class AjaxController {
    /**
     *
     * @author: COS
     * @return:
     * @time: 2022/3/9 11:34
     * @description: 直接返回的字符串是发送给逻辑视图名
     *
     * @ResponseBody 把返回出去的对象或字符串转为json
     * 如果是普通的字符串就会直接写出字符串
     * 如果是对象就会自动转为json字符串
     *
     * @ResponseBody 配合ajax使用 返回字符串或者json字符串使用的
     */
    @RequestMapping("/d1")
    @ResponseBody
    public String hello(){
        System.out.println("进入d1");
        return "admin";
    }
    @RequestMapping("/getUserOne")
    @ResponseBody
    public String getUserOne() throws JsonProcessingException {
        User u = new User(1,"懂王","不明",20,new Date());
        //创建jackson处理的对象
        ObjectMapper om = new ObjectMapper();
        //调用方法把对象写出为json字符串
        String string = om.writeValueAsString(u);
        return string;
    }
    /**
     *
     * @author: COS
     * @return:
     * @time: 2022/3/9 11:55
     * @description:
     * 在返回值写要返回的对象
     * springmvc就会自动使用jackson来帮助我们转换为Json
     * 返回出
     * new User(2,"懂王门","应该是男?",20,new Date());
     * {"id":2,"name":"懂王门","sex":"应该是男?","age":20,"bornDate":"13518131353"}
     *
     * [{"id":2,"name":"懂王门","sex":"应该是男?","age":20,"bornDate":"13518131353"},
     * {"id":2,"name":"懂王门","sex":"应该是男?","age":20,"bornDate":"13518131353"},
     * {"id":2,"name":"懂王门","sex":"应该是男?","age":20,"bornDate":"13518131353"}]
     */
    @RequestMapping("/getUserTwo")
    @ResponseBody
    public User getUserTwo(){
        User u = new User(2,"懂王门","应该是男?",20,new Date());
        System.out.println("xx");
        return u;
    }

    @RequestMapping("/getUserList")
    @ResponseBody
    public List<User> getUserList(){
        List<User> userList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            userList.add(new User(1+i, "zs"+i, "M", 18+i,null));
        }
        return userList;
    }

    @RequestMapping("/checkUsername/{username}")
    @ResponseBody
            public String checkUsername(@PathVariable String username){
                String name = "admin";
                if (username.equals(name)) {
                    return "1";
                }else{
                    return "0";
        }
    }


}
